package com.zhinan.exception;

import com.zhinan.common.R;
import com.zhinan.common.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.CryptoException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

/**
 * @Description: controller层全局统一处理异常
 * @Author: ZhiNan
 * @Date: 2023-04-20 15:47
 * @Version: 1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理由service层抛出的异常
     */
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public R seviceExceptionHandler(ServiceException e) {
        return R.fail(e.getCode(), e.getMsg());
    }


    /**
     * 处理系统内部500异常
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R systemExceptionHandler(Exception e) {
        log.error("返回出现异常....");
        return R.fail();
    }

    /**
     * 处理@Valid注解校验异常
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public R bindExceptionHandler(BindException e) {
        List<ObjectError> allErrors = e.getAllErrors();
        String msg = null;
        if (!allErrors.isEmpty()) {
            msg = allErrors.get(0).getDefaultMessage();
        }
        return R.fail(SysConstant.ERROR_CODE, msg);
    }

}
